<template>
  <div class="login-container">
    <van-nav-bar title="黑马头条" fixed />
    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        label="手机号码"
        placeholder="请输入手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          ,
          { pattern: /^1\d{10}$/, message: '请填写正确的手机号' },
        ]"
      />
      <van-field
        v-model="form.code"
        type="password"
        label="登录密码"
        placeholder="请输入密码"
        required
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/userAPI'
import { mapMutations } from 'vuex'
export default {
  // 组件的name属性值要首字母大写
  name: 'Login',
  data () {
    return {
      form: {
        mobile: '18728581587',
        code: '246810'
      }
    }
  },
  methods: {
    ...mapMutations(['updateTokenInfo']),
    async onSubmit () {
      // console.log(this.form)
      const { data: res } = await loginAPI(this.form)
      // console.log(res)
      if (res.message === 'OK') {
        // 证明登录成功
        // token存储本地
        // localStorage.setItem('token', JSON.stringify(res.data))
        // 把token信息存储到vuex中
        this.updateTokenInfo(res.data)
        // 跳转首页
        // 动态获取登录成功之后要导航到哪个地址
        const navPath = this.$route.query.pre || '/'
        this.$router.replace(navPath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  padding-top: 46px;
}
</style>
